package com.happystudy.serviceImpl;

import com.happpystudy.model.User;
import com.happpystudy.model.course.*;
import com.happpystudy.service.*;
import com.happystudy.mapper.CourseJoinStudentMapper;
import com.happystudy.mapper.CourseMapper;
import com.happystudy.mapper.CourseTeacherMapper;
import com.happystudy.util.KeyUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class CourseServiceImpl implements CourseService {

    @Resource
    CourseMapper courseMapper;

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    CourseScheduleKeyService courseScheduleKeyService;

    @Resource
    CourseTeacherService courseTeacherService;

    @Resource
    CourseJoinStudentMapper courseJoinStudentMapper;

    @Resource
    CourseTeacherMapper courseTeacherMapper;

    @Resource
    UserService userService;

    @Resource
    CourseJoinStudentService courseJoinStudentService;



    @Override
    public Course queryCourseByCourseKey(CourseKey courseKey) {
        String redisKey = KeyUtil.joinKey(courseKey);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Course>(Course.class));
        Course course = (Course) redisTemplate.opsForValue().get(redisKey);

        if (course!=null){
            System.out.println("我是redis查出来的数据"+course.toString());
        }else {
            System.out.println("redis未查出数据");
        }

        if (course==null){
            course = courseMapper.selectByPrimaryKey(courseKey);
            if (course!=null){
                 redisTemplate.opsForValue().set(redisKey,course);
            }
        }
        return course;
    }



    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int doCreateCourse(Course course) {
        Integer userId = course.getUserId();


        User user = userService.returnUserInfoByUserID(userId);
        System.out.println("1.查询当前user结果"+user);
        if (!"eductor".equalsIgnoreCase(user.getRole())){
            return -1;
        }

        redisTemplate.setKeySerializer(new StringRedisSerializer());
//
        int courseResult = insertSelective(course);
//
//
        List<CourseScheduleKey> courseScheduleKeys = course.getTimeList();
        int targetResult = courseScheduleKeys.size();
        int courseScheduleKeyResult = courseScheduleKeyService.insertSelectiveByList(courseScheduleKeys);

        CourseTeacher courseTeacher = new CourseTeacher();
        courseTeacher.setCourseId(course.getCourseId());
        courseTeacher.setUsername(user.getUsername());
        courseTeacher.setCourseGroup(course.getCourseGroup());
        courseTeacher.setUniId(user.getUniId());
        courseTeacher.setUserId(user.getUserId());

        int courseTeacherResult = courseTeacherService.insertSelective(courseTeacher);

        if (courseResult>0 && courseScheduleKeyResult>0 && courseTeacherResult>0 && targetResult==courseScheduleKeyResult){
            String redisKey = KeyUtil.joinKey(course);
            redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Course>(Course.class));
            redisTemplate.opsForValue().set(redisKey,course);

            redisKey = KeyUtil.joinKey(courseTeacher);
            redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<CourseTeacher>(CourseTeacher.class));
            redisTemplate.opsForSet().add(redisKey,courseTeacher);

            return courseResult;
        }else {
            throw new RuntimeException("Insert failed");
        }

    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int insertSelective(Course course) {
        int result;
        result = courseMapper.insertSelective(course);
        return result;
    }

    @Override
    public List<CourseTeacher> queryCoursesByUserId(Integer userId,String role) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        List<CourseTeacher> courses=null;
        if ("eductor".equalsIgnoreCase(role)){
            redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<CourseTeacher>(CourseTeacher.class));
            String redisKey = KeyUtil.COURSE_TEACHER_KEY +":"+userId.toString();
            Set<CourseTeacher> coursesSet = redisTemplate.opsForSet().members(redisKey);
            courses = new ArrayList<>(coursesSet);
            if (courses.size()==0){
                courses =  courseTeacherMapper.selectCourseTeachersByUserId(userId);
                if (courses!=null){
                    for (CourseTeacher courseJoinStudent:courses){
                        redisTemplate.opsForSet().add(redisKey,courseJoinStudent);
                    }
                }
            }
        }else {
            System.out.println("我是测试1我从表中查出数据");
            redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(CourseJoinStudent.class));
            String redisKey = KeyUtil.COURSE_STUDENT_KEY +":"+userId.toString();
            Set<CourseJoinStudent> coursesSet = redisTemplate.opsForSet().members(redisKey);
            courses = new ArrayList<>(coursesSet);
            if (courses.size()==0){
                courses =  courseJoinStudentMapper.selectCourseTeachersByUserId(userId);
                if (courses!=null){
                    for (CourseTeacher courseJoinStudent:courses){
                        redisTemplate.opsForSet().add(redisKey,courseJoinStudent);
                    }

                }
            }
        }

        return courses;
    }

    /**
     * 判断course是否存在 如果存在返回true 否则false
     * @param record 需要查询的Course
     * @return 存在返回true
     */
    @Override
    public Course isCourseExist(Course record) {
        return this.queryCourseByCourseKey(record);
    }

    @Override
    public Boolean verifyCourseCode(Course course, Course record){
        return course.getCoursePassword().equals(record.getCoursePassword());
    }


    /**
     * 执行加入course操作
     * 1.判断课程是否存在
     * 2.判断密码是否正确
     * 3.操作coursejpinstudent表加入数据
     * @param recode
     * @return
     */
    @Override
    public int doJoinCourse(Course recode){
        int result = 0;
        Course newCourse = this.isCourseExist(recode);
        if(newCourse==null){
            return -1;
        }


        if(!this.verifyCourseCode(newCourse,recode)){
            return -2;
        }
        CourseJoinStudent courseJoinStudent = new CourseJoinStudent();
        courseJoinStudent.setCourseGroup(newCourse.getCourseGroup());
        courseJoinStudent.setCourseId(newCourse.getCourseId());
        courseJoinStudent.setUniId(newCourse.getUniId());
        courseJoinStudent.setUserId(recode.getUserId());


        result = courseJoinStudentService.insertCourseJoinStudent(courseJoinStudent);
        return result;
    }

    @Override
    public List<User> queryAllUserByCourseKey(CourseKey courseKey){
        List<User> users = new ArrayList<>();

        //查Teacher
        List<User> users1 = courseTeacherService.selectAllUserByCourseKey(courseKey);
        List<User> users2 = courseJoinStudentService.selectAllUserByCourseKey(courseKey);
        if (users1!=null) {
            users.addAll(users1);
        }
        if (users2!=null){
            users.addAll(users2);
        }
        System.out.println(users);
        return users;
    }

    @Override
    public  List<Course> queryCourseByCourseId(CourseKey course){
        return courseMapper.selectCourseByCourseIdAndUniId(course);
    }

    @Override
    public List<Course> queryAllCourseByUserId(Integer userId) {

        return courseMapper.selectCoursesByUserId(userId);
    }

}
